package com.mywork.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ciko.code.bean.AttendanceRecordBaen;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpClient;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.AttendanceRecordReq;
import com.ciko.code.utils.NetWorkUtils;
import com.ciko.code.utils.Util;
import com.ciko.code.views.pullrefresh.PullToRefreshBase;
import com.ciko.code.views.pullrefresh.PullToRefreshListView;
import com.mywork.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class AttendanceRecordActivity
        extends
        Activity
        implements
        HttpResponseListener {

    private ImageView img_back;
    private PullToRefreshListView list_view;

    private ArrayList<AttendanceRecordBaen> list;
    private ArrayList<AttendanceRecordBaen> datas;
    private AttendanceRecordAdapter attenAdapter;
    private LinearLayout llNoneTip;
    private int stutas = 1;
    private List<String> l;
    private List<String> r;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance_record);

        datas = new ArrayList<AttendanceRecordBaen>();
        r = new ArrayList<String>();
        llNoneTip = (LinearLayout) findViewById(R.id.ll_none_tip);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        attenAdapter = new AttendanceRecordAdapter();
        list_view = (PullToRefreshListView) findViewById(R.id.list_view);
//		        pullToRefreshListView.setPullLoadEnabled(true);
//		        pullToRefreshListView.setScrollLoadEnabled(true);
        list_view.setPullLoadEnabled(true);
        //list_view.setScrollLoadEnabled(true);
        list_view.getRefreshableView().setAdapter(attenAdapter);
        //        if (!TextUtils.isEmpty(SharedPreferencesUtils.get(AttendanceRecordActivity.this, "datetitle", null).toString())) {
        //            String DateTitle = SharedPreferencesUtils.get(AttendanceRecordActivity.this, "datetitle", null).toString();
        //            list_view.setLastUpdatedLabel(DateTitle);
        //
        //        } else {
        //            SharedPreferencesUtils.put(AttendanceRecordActivity.this, "datetitle", getDateTitle(System.currentTimeMillis()));
        //            list_view.setLastUpdatedLabel(getDateTitle(System.currentTimeMillis()));
        //        }

        list_view.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final Intent intent = new Intent(AttendanceRecordActivity.this, AttendanceDetails.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("att", datas.get(position));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        doHttpRequst(0, 15);

        list_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                //doRequestHttp(new AttendanceRecordReq(0, 20));
                doHttpRequst(0, 15);
                stutas = 3;

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载
                // doRequestHttp(new AttendanceRecordReq((long) SharedPreferencesUtils.get(getActivity(), "lastCreateTime", null), 20));
                doHttpRequst(datas.get(datas.size() - 1).getCreateTime(), 15);
                stutas = 2;
            }
        });

        //        FragmentManager fm = getFragmentManager();
        //        FragmentTransaction ft = fm.beginTransaction();
        //        ft.replace(R.id.lin_layout, new AttendanceRecordFragment()).commit();
    }

    private String getDateHead(long curr) {
        Date date = new Date(curr);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private String getDateContent(long curr) {
        Date date = new Date(curr);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    private String getDateTitle(long curr) {
        Date date = new Date(curr);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
        return format.format(date);
    }

    @Override
    public void onRequestStart(String tag) {

    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        list_view.onPullDownRefreshComplete();
        list_view.onPullUpRefreshComplete();
        list = (ArrayList<AttendanceRecordBaen>) response.getReturnObject();
        if (stutas == 1) {
            //首次加载
            if (list == null || list.size() <= 0) {
                llNoneTip.setVisibility(View.VISIBLE);
                list_view.setVisibility(View.GONE);
            } else {
                if (list.size() < 15) {
                    list_view.setScrollLoadEnabled(false);
                } else {
                    list_view.setScrollLoadEnabled(true);
                }
                llNoneTip.setVisibility(View.GONE);
                list_view.setVisibility(View.VISIBLE);
                setFirstData(list);
                attenAdapter.notifyDataSetChanged();
            }
        } else if (stutas == 2) {
            //上拉
            if (list == null || list.size() <= 0) {
                Util.showToast(AttendanceRecordActivity.this, "没有更多数据了");
            } else {
                setUpData(list);
            }
        } else {
            //下拉
            if (list != null && list.size() > 0) {
                if (list.size() < 15) {
                    list_view.setScrollLoadEnabled(false);
                } else {
                    list_view.setScrollLoadEnabled(true);
                }
                setDownData(list);
                llNoneTip.setVisibility(View.GONE);
                list_view.setVisibility(View.VISIBLE);
            } else {
                llNoneTip.setVisibility(View.VISIBLE);
                list_view.setVisibility(View.GONE);
            }
        }

    }

    //为首次加载填充数据
    private void setFirstData(ArrayList<AttendanceRecordBaen> list) {
        AttendanceRecordBaen arb;
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                //添加第一个头
                if (i == 0) {
                    arb = new AttendanceRecordBaen();
                    arb.setType(0);
                    arb.setCreateTime(list.get(i).getCreateTime());
                    arb.setDateTitle(getDateHead(list.get(i).getCreateTime()));
                    datas.add(arb);
                }
                if ((i + 1) != list.size()) {
                    if (getDateHead(list.get(i).getCreateTime()).equals(getDateHead(list.get(i + 1).getCreateTime()))) {
                        list.get(i).setType(1);
                        datas.add(list.get(i));
                    } else {
                        list.get(i).setType(1);
                        datas.add(list.get(i));

                        arb = new AttendanceRecordBaen();
                        arb.setType(0);
                        arb.setCreateTime(list.get(i + 1).getCreateTime());
                        arb.setDateTitle(getDateHead(list.get(i + 1).getCreateTime()));
                        datas.add(arb);
                    }
                } else {
                    list.get(list.size() - 1).setType(1);
                    datas.add(list.get(list.size() - 1));
                }
            }

        }
    }

    //为下拉填充数据
    private void setDownData(ArrayList<AttendanceRecordBaen> list) {
        AttendanceRecordBaen arb;
        if (list != null && list.size() > 0) {
            arb = new AttendanceRecordBaen();
            if (datas != null && datas.size() > 0) {
                datas.clear();
            }
            for (int i = 0; i < list.size(); i++) {
                //添加第一个头
                if (i == 0) {
                    arb = new AttendanceRecordBaen();
                    arb.setType(0);
                    arb.setCreateTime(list.get(i).getCreateTime());
                    arb.setDateTitle(getDateHead(list.get(i).getCreateTime()));
                    datas.add(arb);
                }
                if ((i + 1) != list.size()) {
                    if (getDateHead(list.get(i).getCreateTime()).equals(getDateHead(list.get(i + 1).getCreateTime()))) {
                        list.get(i).setType(1);
                        datas.add(list.get(i));
                    } else {
                        list.get(i).setType(1);
                        datas.add(list.get(i));

                        arb = new AttendanceRecordBaen();
                        arb.setType(0);
                        arb.setCreateTime(list.get(i + 1).getCreateTime());
                        arb.setDateTitle(getDateHead(list.get(i + 1).getCreateTime()));
                        datas.add(arb);
                    }
                } else {
                    list.get(list.size() - 1).setType(1);
                    datas.add(list.get(list.size() - 1));
                }
            }
            attenAdapter.notifyDataSetChanged();
        }
    }

    //为上拉加载填充数据
    private void setUpData(ArrayList<AttendanceRecordBaen> list) {
        AttendanceRecordBaen arb;
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (!getDateHead(datas.get(datas.size() - 1).getCreateTime()).equals(getDateHead(list.get(i).getCreateTime()))) {
                    arb = new AttendanceRecordBaen();
                    arb.setType(0);
                    arb.setCreateTime(list.get(i).getCreateTime());
                    arb.setDateTitle(getDateHead(list.get(i).getCreateTime()));
                    datas.add(arb);
                }

                if ((i + 1) != list.size()) {
                    if (getDateHead(list.get(i).getCreateTime()).equals(getDateHead(list.get(i + 1).getCreateTime()))) {
                        list.get(i).setType(1);
                        datas.add(list.get(i));
                    } else {
                        list.get(i).setType(1);
                        datas.add(list.get(i));

                        arb = new AttendanceRecordBaen();
                        arb.setType(0);
                        arb.setCreateTime(list.get(i + 1).getCreateTime());
                        arb.setDateTitle(getDateHead(list.get(i + 1).getCreateTime()));
                        datas.add(arb);
                    }
                } else {
                    list.get(list.size() - 1).setType(1);
                    datas.add(list.get(list.size() - 1));
                }

            }
            attenAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        list_view.onPullDownRefreshComplete();
        list_view.onPullUpRefreshComplete();
        if (NetWorkUtils.isConnected(AttendanceRecordActivity.this))
            Util.showToast(AttendanceRecordActivity.this, "加载失败，请重试");
    }

    class AttendanceRecordAdapter
            extends
            BaseAdapter {

        @Override
        public int getItemViewType(int position) {
            return datas.get(position).getType();
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getCount() {
            if (datas != null && datas.size() > 0)
                return datas.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        //        @Override
        //        public boolean areAllItemsEnabled() {
        //            return false;
        //        }

        @Override
        public boolean isEnabled(int position) {
            if (datas.get(position).getType() == 0) {
                return false;
            }
            return super.isEnabled(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderTitle holderTitle;
            ViewHolderContnet holderContent;
            int type = getItemViewType(position);
            if (convertView == null) {
                switch (type) {
                    case 0:
                        //显示头部布局
                        convertView = LayoutInflater.from(AttendanceRecordActivity.this).inflate(R.layout.recird_activity_title, null);
                        holderTitle = new ViewHolderTitle();
                        holderTitle.txt_title_date = (TextView) convertView.findViewById(R.id.txt_title_date);
                        holderTitle.txt_title_date.setText(datas.get(position).getDateTitle());

                        convertView.setTag(holderTitle);
                        break;

                    case 1:
                        //显示内容布局
                        convertView = LayoutInflater.from(AttendanceRecordActivity.this).inflate(R.layout.record_activity_content, null);
                        holderContent = new ViewHolderContnet();
                        holderContent.txt_content_date = (TextView) convertView.findViewById(R.id.txt_content_date);
                        holderContent.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
                        holderContent.txt_content_date.setText(getDateContent(datas.get(position).getVisitTime()));
                        holderContent.txt_content.setText(datas.get(position).getCustName());
                        convertView.setTag(holderContent);
                        break;
                }
            } else {
                switch (type) {
                    case 0:
                        holderTitle = (ViewHolderTitle) convertView.getTag();
                        holderTitle.txt_title_date.setText(datas.get(position).getDateTitle());
                        break;

                    case 1:
                        holderContent = (ViewHolderContnet) convertView.getTag();
                        holderContent.txt_content_date.setText(getDateContent(datas.get(position).getVisitTime()));
                        holderContent.txt_content.setText(datas.get(position).getCustName());
                        break;
                }
            }
            return convertView;
        }
    }

    class ViewHolderTitle {
        TextView txt_title_date;
    }

    class ViewHolderContnet {
        TextView txt_content_date;
        TextView txt_content;
    }

    private void doHttpRequst(long lastCreateTime, int length) {
        HttpClient.getInstance(AttendanceRecordActivity.this).post(new AttendanceRecordReq(lastCreateTime, length), this);
    }
}
